﻿using orderCreater.Model.WSY;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace orderCreater
{
    public partial class Frm531Jf : Form
    {
        public OrderCreaterModel OCM = new OrderCreaterModel();
        public WSY_CreaterModel OCM_WSY = new WSY_CreaterModel();

        public Frm531Jf()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.jf_bgw.WorkerSupportsCancellation = true;
            this.jf_bt_stop.Enabled = false;
            this.jf_tb_goodsIds.Text = ConfigurationManager.AppSettings["goodsIds-531Order"];
        }
        private string CreateDelayTime(string sendTime)
        {
            string returnString = string.Empty;
            Random rd = new Random();
            string dateStr = DateTime.Parse(sendTime).ToShortDateString();
            int timeStr = DateTime.Parse(sendTime).Hour - 2 + rd.Next(0, 2);

            string h = timeStr.ToString();
            string m = rd.Next(0, 31).ToString();
            string s = rd.Next(0, 60).ToString();

            if (h.Length < 2)
            {
                h = "0" + h;
            }
            if (m.Length < 2)
            {
                m = "0" + m;
            }
            if (s.Length < 2)
            {
                s = "0" + s;
            }
            returnString = dateStr + " " + h + ":" + m + ":" + s;
            return returnString;
        }

        private string CreateFinnshedTime(string sendTime)
        {
            string returnString = string.Empty;
            Random rd = new Random();
            int addD = rd.Next(0, 4);
            int addH = rd.Next(1, 24);
            int addM = rd.Next(0, 60);
            int addS = rd.Next(0, 60);
            DateTime newDate = DateTime.Parse(sendTime).AddDays(addD).AddHours(addH).AddMinutes(addM).AddSeconds(addS);

            returnString = newDate.ToShortDateString() + " " + newDate.Hour.ToString() + ":" + newDate.Minute.ToString() + ":" + newDate.Second.ToString();

            return returnString;
        }
        private void jf_bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = (BackgroundWorker)sender;
            this.jf_bt_stop.Enabled = true;
            this.jf_bt_start.Enabled = false;
            this.jf_tb_goodsIds.Enabled = false;
            this.jf_tb_shopIds.Enabled = false;
            this.jf_dt_time.Enabled = false;
            StringBuilder _logs = new StringBuilder();
            int post_err_cnt = 0;
            List<Db_shops> _shop = OCM_WSY.SelectShopsByIDs(this.jf_tb_shopIds.Text.ToString().Trim());
            for (int i = 0; i < _shop.Count; i++) 
            {
                if (!worker.CancellationPending)
                {
                    ///获取新增用户
                    WDH_REGISTER new_user = cb_user.Checked ? OCM.WSYExistUser() : OCM.WSYNewUser();
                    if (new_user.status == 200)
                    {
                        ///获取收货地址
                        WDH_AddrRange new_addr = OCM.WSYNormalAddr();
                        if (new_addr.status == 200 && new_addr.data.Count > 0)
                        {
                            Db_member buyer = OCM_WSY.SelectBuyerById(new_user.data.member_id);
                            if (buyer == null) continue;
                            Db_goods goods = OCM_WSY.SelectGoodsByIds(this.jf_tb_goodsIds.Text);
                            if (goods == null) continue;
            

                            string orderCode = OCM.CreateOrderCode();
                            string payCode = OCM.createPayCode(new_user.data.member_id);
                            string orderTimeStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            if (bd_cb.Checked)
                            {
                                orderTimeStr = OCM.CreateOrderTime(this.jf_dt_time.Value.ToString("yyyy-MM-dd"));
                            }
                            string orderTime = ((DateTime.Parse(orderTimeStr).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                            string requestTime = ((DateTime.Parse(OCM.CreateSendTime(orderTimeStr)).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                            string payTimeStr = OCM.CreatePayTime(orderTimeStr, tb_jiange.Text);
                            string payTime = ((DateTime.Parse(payTimeStr).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                            string delayTime = ((DateTime.Parse(CreateDelayTime(OCM.CreateSendTime(orderTimeStr))).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                            string finnshedTime = ((DateTime.Parse(CreateFinnshedTime(OCM.CreateSendTime(orderTimeStr))).ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();
                            string payType = "alipay";
                            string addressLength = OCM.StringToByte(new_addr.data[0].address, Encoding.UTF8).Length.ToString();
                            string orderRemarks = OCM.getWSYOrderRemark();
                            
                            Db_order add_order = new Db_order();
                            add_order.order_sn = Convert.ToInt64(orderCode);
                            add_order.pay_sn = Convert.ToInt64(payCode);
                            add_order.store_id = _shop[i].Id;
                            add_order.store_name = _shop[i].Name;
                            add_order.buyer_id = buyer.member_id;
                            add_order.buyer_name = buyer.member_name;
                            add_order.buyer_email = buyer.member_email;
                            add_order.add_time = (DateTime.Parse(orderTimeStr).ToUniversalTime().Ticks - 621355968000000000) / 10000000;
                            add_order.payment_code = "alipay";
                            add_order.payment_time = (DateTime.Parse(payTimeStr).ToUniversalTime().Ticks - 621355968000000000) / 10000000;
                            add_order.goods_amount = goods.goods_price;
                            add_order.order_amount = goods.goods_price;
                            add_order.order_from = 1;
                            add_order.request_delivery_time = (DateTime.Parse(OCM.CreateSendTime(orderTimeStr)).ToUniversalTime().Ticks - 621355968000000000) / 10000000;
                            //add_order.is_zc = 1;
                            add_order.type_status = 2;

                            Db_order_common order_common = new Db_order_common();
                            order_common.store_id = _shop[i].Id;
                            order_common.order_message = orderRemarks;
                            order_common.reciver_name = new_addr.data[0].name;
                            order_common.reciver_info = "a:6:{s:5:\"phone\";s:11:\"" + new_addr.data[0].mobile + "\";s:9:\"mob_phone\";s:11:\"" + new_addr.data[0].mobile + "\";s:9:\"tel_phone\";s:0:\"\";s:7:\"address\";s:" + addressLength + ":\"" + new_addr.data[0].address + "\";s:4:\"area\";s:0:\"\";s:6:\"street\";s:0:\"\";}";
                            order_common.reciver_province_id = new_addr.data[0].province_id;
                            order_common.reciver_city_id = new_addr.data[0].city_id;
                            order_common.reciver_area_id = new_addr.data[0].area_id;
                            order_common.invoice_info = "a:0:{}";

                            Db_order_goods order_goods = new Db_order_goods();
                            order_goods.goods_id = goods.goods_id;
                            order_goods.goods_name = goods.goods_name;
                            order_goods.goods_price = goods.goods_price;
                            order_goods.goods_num = 1;
                            order_goods.goods_image = goods.goods_image;
                            order_goods.goods_pay_price = goods.goods_price;
                            order_goods.store_id = _shop[i].Id;
                            order_goods.buyer_id = buyer.member_id;
                            order_goods.gc_id = goods.gc_id;

                            Db_order_pay order_pay = new Db_order_pay();
                            order_pay.pay_sn = Convert.ToInt64(payCode);
                            order_pay.buyer_id = buyer.member_id;

                            string order_id = OCM_WSY.AddOrder(add_order);

                            if (order_id != "" && order_id != "" && order_id != "-1")
                            {
                                if (this.sync_alipay_cb.Checked == true)
                                {
                                    syncAlipay(orderCode, goods.goods_price.ToString(), buyer.member_email, buyer.member_name, payTimeStr);
                                }

                                _logs.Insert(0, new_addr.data[0].name + " " + new_addr.data[0].mobile + " " + new_addr.data[0].province_id + " " + new_addr.data[0].city_id + " " + new_addr.data[0].area_id + " " + new_addr.data[0].address + "\r\n");

                              
                                //string sql_log_pay = "INSERT INTO `db_order_log` (`order_id`, `log_msg`, `log_time`, `log_role`, `log_user`, `log_orderstate`) VALUES (" + order_id + ", '收到了货款', '" + payTime + "', '商家', 'dl_sk_" + new_addr.data[0].city_id + "', '20');";
                                //OCM.ExecuteNonSql(sql_log_pay);
                                //string sql_log_delay = "INSERT INTO `db_order_log` (`order_id`, `log_msg`, `log_time`, `log_role`, `log_user`, `log_orderstate`) VALUES (" + order_id + ", '发出了货物 ( 编辑了发货信息 )', '" + delayTime + "', '商家', 'dl_ps_" + new_addr.data[0].city_id + "', '30');";
                                //OCM.ExecuteNonSql(sql_log_delay);
                                //string sql_log_finnshed = "INSERT INTO `db_order_log` (`order_id`, `log_msg`, `log_time`, `log_role`, `log_user`, `log_orderstate`) VALUES (" + order_id + ", '签收了货物', '" + finnshedTime + "', '买家', '" + buyer.member_name + "', '40');";
                                //OCM.ExecuteNonSql(sql_log_finnshed);
                                //OCM.ExecuteNonSql("update db_order_common set shipping_time='" + delayTime + "' where order_id=" + order_id + ";");
                                //OCM.ExecuteNonSql("update db_shops set jd=jd-1 where id=" + _shop[i].ID + ";");
                                //OCM.ExecuteNonSql("INSERT INTO `db_v_order` (`orderId`, `orderCode`, `shopId`) VALUES (" + order_id + ", '" + orderCode + "', " + _shop[i].ID + ");");
                                ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

                                _logs.Insert(0, "[" + DateTime.Now + "]成功录入一条订单信息到店铺：[" + _shop[i].Name + "]。\r\n");

                                this.jf_lb_status.Text = "运行中……";

                                this.jf_tb_logs.Text = _logs.ToString();

                                this.jf_lb_count.Text = _shop.Count.ToString() + "-" + (i + 1).ToString() + "=" + (_shop.Count - i - 1).ToString();

                                this.ok_id.Text = this.ok_id.Text + "," + _shop[i].Id.ToString();
                            }
                        }
                        else
                        {
                            _logs.Insert(0, "[" + DateTime.Now + "]获取收货地址失败：" + new_addr.msg + "。\r\n");
                            this.jf_tb_logs.Text = _logs.ToString();
                            post_err_cnt++;
                            if (post_err_cnt > 10)
                            {
                                this.jf_lb_status.Text = "停止中……";
                                jf_bgw.CancelAsync();
                            }
                        }
                    }
                    else
                    {
                        _logs.Insert(0, "[" + DateTime.Now + "]获取下单人信息失败：" + new_user.msg + "。\r\n");
                        this.jf_tb_logs.Text = _logs.ToString();
                        post_err_cnt++;
                        if (post_err_cnt > 10)
                        {
                            this.jf_lb_status.Text = "停止中……";
                            jf_bgw.CancelAsync();
                        }
                    }



                    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    if (bd_cb.Checked != true)
                    {
                        Random rd_sl = new Random();
                        int t_sl = rd_sl.Next(20 * 1000, Int32.Parse(this.tb_jiange.Text) * 1000);
                        System.Threading.Thread.Sleep(t_sl);
                    }
                }
                if (i == (_shop.Count - 1))
                {
                    e.Cancel = true;
                }
            }
            this.jf_lb_status.Text = "已停止";
            this.jf_bt_stop.Enabled = false;
            this.jf_bt_start.Enabled = true;

            this.jf_tb_goodsIds.Enabled = true;
            this.jf_tb_goodsIds.Enabled = true;
            this.jf_dt_time.Enabled = true;
        }

        private void jf_bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                this.jf_lb_status.Text = "已停止！";
            }
        }

        private void jf_bt_start_Click(object sender, EventArgs e)
        {
            if (this.jf_tb_goodsIds.Text.Length < 1) 
            {
                MessageBox.Show("请输入店铺ID。");
            }
            else if (this.jf_tb_goodsIds.Text.Length < 1) 
            {
                MessageBox.Show("请输入产品ID。");
            }
            else 
            {
                this.jf_bgw.RunWorkerAsync();
            }
        }

        private void jf_bt_stop_Click(object sender, EventArgs e)
        {
            this.jf_lb_status.Text = "停止中……";

            jf_bgw.CancelAsync();
        }
        public static string syncAlipay(string _orderSn, string _orderPrice, string _account, string _fullName, string _tradeTime)
        {
            try
            {
                string url = "orderNo=" + _orderSn + "&";
                url = url + "tradeAmount=" + _orderPrice + "&";
                url = url + "otherAccountEmail=" + _account + "&";
                url = url + "otherAccountFullname=" + _fullName + "&";
                url = url + "sourceType=" + 1 + "&"; // 来源:1为531,2为我订花
                url = url + "tradeTime=" + _tradeTime;
                // string formUrl = "http://sync?.qqxhsd.com/api/trade/add";
                string formUrl = "https://alipay.22ca.com/index.php/Api/insertOrder3";
                string formData = url;                               //提交的参数

                //注意提交的编码 这边是需要改变的 这边默认的是Default：系统当前编码
                byte[] postData = Encoding.UTF8.GetBytes(formData);

                // 设置提交的相关参数 
                HttpWebRequest request = WebRequest.Create(formUrl) as HttpWebRequest;
                Encoding myEncoding = Encoding.UTF8;
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR  3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.ContentLength = postData.Length;

                // 提交请求数据 
                System.IO.Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);
                outputStream.Close();

                HttpWebResponse response;
                Stream responseStream;
                StreamReader reader;
                string srcString;
                response = request.GetResponse() as HttpWebResponse;
                responseStream = response.GetResponseStream();
                reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8"));
                srcString = reader.ReadToEnd();
                string result = srcString;   //返回值赋值
                reader.Close();
                return result;
            }
            catch
            {
                return "error";
            }
        }

        private void bd_cb_CheckedChanged(object sender, EventArgs e)
        {
            if (this.bd_cb.Checked == true)
            {
                this.jf_dt_time.Enabled = true;
            }
            else
            {
                this.jf_dt_time.Enabled = false;

            }
        }

    }
}
